{
    // Script will bail out after this many milliseconds.
    var timeout = 2000;

    var start = new Date();
    start = start.getTime();

    var redirect = new RegExp("^http://www\\.amazon\\.(com|ca|co\\.jp|de|fr|co\\.uk)/(exec/obidos|o)/redirect", "i");
    var asin     = new RegExp("^http://www\\.amazon\\.(com|ca|co\\.jp|de|fr|co\\.uk)/(exec/obidos|o)/ASIN\\d?/\\w{10}/(ref=nosim/)?([^/?]+)", "i");
    var isbn     = new RegExp("^http://www\\.amazon\\.(com|ca|co\\.jp|de|fr|co\\.uk)/(exec/obidos|o)/ISBN=\\w{10}/(ref=nosim/)?([^/?]+)A", "i");
    var mp       = new RegExp("^http://www\\.amazon\\.(com|ca|co\\.jp|de|fr|co\\.uk)/gp/associates/link-types/marketplace", "i");

    var allLinks = document.getElementsByTagName('a');
    var imp = {};

    var orgUnit = {
        'com'   : 1,
        'ca'    : 15,
        'co.jp' : 9,
        'de'    : 3,
        'fr'    : 8,
        'co.uk' : 2
    };

    var ccmid = {
        'as2' : '374929',
       '-as2' : '9325',
        'as3' : '373489',
        'am2' : '374925',
       '-am2' : '9325',
        'am3' : '373493'
    };

    var camp = '211189';
    var timeoutReached = false;

    // Do not decorate links in unsupported browsers
    var amazonTreatment = false;
    var agent = new String(navigator.userAgent);
    if (agent.match(/(MSIE.*Windows|Firefox|Netscape|Windows.*Gecko|Safari\/)/))
    {
        // Set treatment cookie if it's not already set
        if (amazon_getcookie('amazon_vf') == null)
        {
            var randy = (Math.random() > 0.5) ? 'on' : 'off';
            amazon_setcookie('amazon_vf', randy);
        }

        // Read treatment cookie
        amazonTreatment = (amazon_getcookie('amazon_vf') == 'on') ? true : false;
    }


    for (var i=0; i < allLinks.length; i++)
    {
        // Check if it's an Amazon redirect link
        var href = new String(allLinks[i].href);
        var results;
        if (results = href.match(redirect))
        {
            var locale = results[1];
            // Change link code to impression-tracked version
            if (href.match(/link_code=asn/))
            {
                var code = ((locale == 'com') && amazonTreatment) ? 'as3' : 'as2';
                href = href.replace(/link_code=asn/, 'link_code=' + code);
                href = href.replace(/creative=\d+/, 'creative=' + ccmid[code]);
                href = href.replace(/camp=\d+/, 'camp=' + camp);
                allLinks[i].href = href;
                var tag = href.match(/tag=([^&]+)/)[1];
                imp = amazon_logImpression(imp, locale, tag, code);
            }
            else if (href.match(/link_code=asm/))
            {
                var code = ((locale == 'com') && amazonTreatment) ? 'am3' : 'am2';
                href = href.replace(/link_code=asm/, 'link_code=' + code);
                href = href.replace(/creative=\d+/,  'creative=' + ccmid[code]);
                href = href.replace(/camp=\d+/, 'camp=' + camp);
                allLinks[i].href = href;
                var tag = href.match(/tag=([^&]+)/)[1];
                imp = amazon_logImpression(imp, locale, tag, code);
            }
            else if (href.match(/link_code=ure/))
            {
                href = href.replace(/link_code=ure/, 'link_code=ur2');
                allLinks[i].href = href;
                var tag = href.match(/tag=([^&]+)/)[1];
                imp = amazon_logImpression(imp, locale, tag, 'ur2');
            }

            else if (href.match(/link_code=as2/))
            {
                // Existing as2 link
                var code = 'as2';
                if ((locale == 'com') && amazonTreatment)
                {
                    code = 'as3';
                    href = href.replace(/link_code=as2/, 'link_code=as3');
                }
                href = href.replace(/creative=\d+/, 'creative=' + ccmid[code]);
                href = href.replace(/camp=\d+/, 'camp=' + camp);
                allLinks[i].href = href;
                var tag = href.match(/tag=([^&]+)/)[1];
                imp = amazon_logImpression(imp, locale, tag, code);
                imp = amazon_logImpression(imp, locale, tag, '-as2', -1);
            }
            else if (href.match(/link_code=am2/))
            {
                // Existing am2 link
                var code = 'am2';
                if ((locale == 'com') && amazonTreatment)
                {
                    code = 'am3';
                    href = href.replace(/link_code=am2/, 'link_code=am3');
                }
                href = href.replace(/creative=\d+/, 'creative=' + ccmid[code]);
                href = href.replace(/camp=\d+/, 'camp=' + camp);
                allLinks[i].href = href;
                var tag = href.match(/tag=([^&]+)/)[1];
                imp = amazon_logImpression(imp, locale, tag, code);
                imp = amazon_logImpression(imp, locale, tag, '-am2', -1);
            }

            else if (!href.match(/link_code=/) && href.match(/tag=([^&]+)/))
            {
                href = href + '&link_code=ur2&camp=' + camp + '&creative=9325';
                allLinks[i].href = href;
                var tag = href.match(/tag=([^&]+)/)[1];
                imp = amazon_logImpression(imp, locale, tag, 'ur2');
            }
        }
        // Check if it's an old-style ASIN link
        else if (results = href.match(asin))
        {
            var locale = results[1];
            var code = ((locale == 'com') && amazonTreatment) ? 'as3' : 'as2';

            // Replace ASIN handler with redirect
            href = href.replace(/ASIN\d?\/(\w{10})\/(ref=nosim\/)?([^\/\?]+).*/i, 'redirect?tag=$3&creative=' + ccmid[code] + '&camp=' + camp + '&link_code=' + code + '&path=ASIN/$1');
            allLinks[i].href = href;
            var tag = results[4];
            imp = amazon_logImpression(imp, locale, tag, code);
        }
        // Check if it's a really-old-style ISBN link
        else if (results = href.match(isbn))
        {
            var locale = results[1];
	    var code = ((locale == 'com') && amazonTreatment) ? 'as3' : 'as2';

            // Replace ISBN handler with redirect
            href = href.replace(/ISBN=(\w{10})\/(ref=nosim\/)?([^\/\?]+)A.*/, 'redirect?tag=$3&creative=' + ccmid[code] + '&camp=' + camp + '&link_code=' + code + '&path=ASIN/$1');
            allLinks[i].href = href;
            var tag = results[4];
            imp = amazon_logImpression(imp, locale, tag, code);
        }
        // Check if it's an old-style marketplace link
        else if (results = href.match(mp))
        {
            var locale = results[1];
	    var code = ((locale == 'com') && amazonTreatment) ? 'am3' : 'am2';

            // Replace marketplace handler with redirect
            var mpTarget = new RegExp('/gp/associates/link-types/marketplace\\.html\\?asin=(\\w{10})&(amp;)?t=([^/]+)');
            href = href.replace(mpTarget, '/exec/obidos/redirect?tag=$3&creative=' + ccmid[code] + '&camp=' + camp + '&link_code=' + code + '&path=tg/stores/offering/list/-/$1/all/$1');
            var mpTarget = new RegExp('/gp/associates/link-types/marketplace\\.html\\?t=([^&]+)&(amp;)?asin=(\\w{10})');
            href = href.replace(mpTarget, '/exec/obidos/redirect?tag=$1&creative=' + ccmid[code] + '&camp=' + camp + '&link_code=' + code + '&path=tg/stores/offering/list/-/$3/all/$3');
            allLinks[i].href = href;
            var tag = href.match(/tag=([^&]+)/)[1];
            imp = amazon_logImpression(imp, locale, tag, code);
        }


        if (amazonTreatment && (locale == 'com'))
        {
            amazon_enhanceLink(allLinks[i]);
        }

        // Have we gone over our time limit?
        var now = new Date();
        now = now.getTime();
        if (now > (start + timeout))
        {
            timeoutReached = true;
            break;
        }
    }

    var tagID;
    var scripts = document.getElementsByTagName('script');
    for (var i=0; i < scripts.length; i++)
    {
        var source = new String(scripts[i].src);
        var tagIDObj;
        if (tagIDObj = source.match(/link-enhancer.*\?tag=([^&]+)/))
        {
            tagID = tagIDObj[1];
            break;
        }
    }



    if (amazonTreatment)
    {
        document.write('<scr' + 'ipt type="text/javascript" src="http://www.amazon.com/gp/associates/jsf/po.html?tag=' + tagID + '"></scr' + 'ipt>');
    }

    var total = 0;

    // Send data to impression recorder via img tags
    for (var locale in imp)
    {
        var tld = (locale == 'co.jp') ? 'jp' : locale;
        for (var tag in imp[locale])
        {
            // Record the fact that this script was served.
            var tc = ((locale == 'com') && amazonTreatment) ? 'pv3' : 'pv2';
            document.write('<img src="http://www.assoc-amazon.' + tld + '/e/ir' +
                  '?l=' + tc +
                  '&t=' + tag +
                  '&o=' + orgUnit[locale] + '" />');

            for (var code in imp[locale][tag])
            {
                var link_code = new String(code);
                link_code = link_code.replace(/^-/, '');
                document.write('<img src="http://www.assoc-amazon.' + tld + '/e/ir' +
                      '?t=' + tag +
                      '&l=' + link_code +
                      '&o=' + orgUnit[locale] +
                      '&creative=' + ccmid[code] +
                      '&camp=' + camp +
                      '&i=' + imp[locale][tag][code] + '" />');

                total += imp[locale][tag][code];
            }
        }
    }

    if (timeoutReached)
    {
        document.write('<img src="http://www.assoc-amazon.com/e/ir?t=' + tagID + '&l=to0&o=1&i=' + total + '" />');
    }
}

function amazon_logImpression(imp, locale, tag, code, count)
{
    if (!count)
    {
        count = 1;
    }

    if (imp[locale])
    {
        if (imp[locale][tag])
        {
            if (imp[locale][tag][code])
            {
                imp[locale][tag][code] = imp[locale][tag][code] + count;
            }
            else
            {
                imp[locale][tag][code] = count;
            }
        }
        else
        {
            imp[locale][tag] = {};
            imp[locale][tag][code] = count;
        }
    }
    else
    {
        imp[locale] = {};
        imp[locale][tag] = {};
        imp[locale][tag][code] = count;
    }

    return imp;
}


// Attach product data to the link
function amazon_enhanceLink(link)
{
    if (!link.name)
    {
        if (link.href.match(redirect))
        {
            var href = new String(link.href);
            var results = href.match(/ASIN\/(\w{10})/);
            if (!results)
            {
                results = href.match(/offering\/list\/-\/(\w{10})/);
            }

            if (results)
            {
                if (href.match(/link_code=as3/))
                {
                    link.name = 'evtst|a|' + results[1];
                }
                else if (href.match(/link_code=am3/))
                {
                    link.name = 'evtst|a|' + results[1];
                }
            }
        }
    }
}

// Cookie functions
function amazon_getcookie(name)
{
    var re = new RegExp(name + "=([^;]+);?");
    var results = re.exec(document.cookie);
    return results ? results[1] : null;
}
function amazon_setcookie(name, value)
{
    // Cookie will expire in a year
    var d = new Date;
    d.setFullYear(d.getFullYear() + 1);
    var host = document.location.host;
    var domain = host.replace(/^www\./, '');
    document.cookie = name + '=' + value + ';domain=.' + domain + ';path=/;expires=' + d.toGMTString();
}
